//
//  PywCommonRequestHelper.m
//  PywCommonSDKDemo
//
//  Created by Ampaw on 2017/8/10.
//  Copyright © 2017年 Ampaw. All rights reserved.
//

#import "PywCommonRequestHelper.h"
#import <CommonCrypto/CommonCrypto.h>
#import "PywCommonDataDealUtils.h"
#import "YYFTAFNetworking.h"
#import "PywCommonDeviceInfo.h"
#import "PywCommonPlatformInfo.h"
#import "PywCommonMutableDictionary.h"
#import "NSString+AES.h"
#import "PywCommonApiManager.h"

NSString *const COMMONSDK_Ver           = @"ver";
NSString *const COMMONSDK_NetworkType   = @"networktype";
NSString *const COMMONSDK_Imei          = @"imei";
NSString *const COMMONSDK_OS            = @"os";
NSString *const COMMONSDK_Model         = @"model";
NSString *const COMMONSDK_IOSVER        = @"ios_ver";

NSString *const COMMONSDK_SdkType       = @"sdk_type";
NSString *const COMMONSDK_GameVerCode   = @"game_version_code";
NSString *const COMMONSDK_GameVerName   = @"game_version_name";
NSString *const COMMONSDK_PromoChannel  = @"promo_channel";
NSString *const COMMONSDK_PromoCode     = @"promo_code";
NSString *const COMMONSDK_Channel_Code  = @"channel_code"; // 联运包ID

@implementation PywCommonRequestHelper

+ (void)requestApiForSdkUrl:(NSString*)urlStr
                    success:(void (^)(NSDictionary *dict))success
                     failer:(void (^)(NSError *error))failer
{
    //1.确定请求路径
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //2.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //3.根据会话对象创建一个Task(发送请求）
    /*
     第一个参数：请求路径
     第二个参数：completionHandler回调（请求完成【成功|失败】的回调）
     data：响应体信息（期望的数据）
     response：响应头信息，主要是对服务器端的描述
     error：错误信息，如果请求失败，则error有值
     注意：
     1）该方法内部会自动将请求路径包装成一个请求对象，该请求对象默认包含了请求头信息和请求方法（GET）
     2）如果要发送的是POST请求，则不能使用该方法
     */
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        if(httpResponse.statusCode == 200){
            // 获得的json先转换成字符串
            NSString *receiveStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            // 将字符串进行AES解密,得到JSON字符串
            receiveStr = [receiveStr aci_decryptWithAES];
            // 去除字符串中的“\0”
            receiveStr = [receiveStr stringByReplacingOccurrencesOfString:@"\0" withString:@""];
            // 将JSON串，转换为字典
            NSDictionary *jsonDict = [[PywCommonApiManager manager] dictionaryWithJsonString:receiveStr];
            NSLog(@"jsonDict: %@",jsonDict.description);
            if (success) {
                success(jsonDict);
            }
        }else{
            NSLog(@"%@",error);
            if (failer) {
                failer(error);
            }
        }
    }];
    //4.执行任务
    [dataTask resume];
}

+(void)requestWithParams:(NSDictionary *)params
          requestBaseUrl:(NSString *)baseUrl
           requestMethod:(NSString *)requestMethod
                complete:(CommonSDKRequestComplete)complete
{
    // 拼接请求Url地址
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", baseUrl, requestMethod];
    // 参数处理
    NSDictionary *requesParams = [self unifiedParames:params];
    if (!requesParams) {
        COMLog(@"\n----------%@:参数类型错误,请联系朋友玩----------",requestMethod);
        return;
    }
    
    // 参数加密
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
    NSMutableArray * mArray = [[NSMutableArray alloc] init];
    [mArray addObject:requesParams];
    NSData * tmpData = [NSJSONSerialization dataWithJSONObject:mArray options:0 error:nil];
    NSData *testData = [PywCommonDataDealUtils encode:tmpData];
    NSString * paramData = [[ NSString alloc] initWithData:testData encoding:enc];
    NSMutableDictionary * mainparams = [NSMutableDictionary dictionary];
    mainparams[@"param"] = paramData;
    
    YYFTAFHTTPRequestSerializer<YYFTAFURLRequestSerialization> *httpRequestSerializer = [YYFTAFHTTPRequestSerializer serializer];
    NSStringEncoding enc1 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
    httpRequestSerializer.stringEncoding = enc1;
    [httpRequestSerializer setTimeoutInterval:60];
    
    NSMutableURLRequest *request = [httpRequestSerializer
                                    multipartFormRequestWithMethod:@"POST"
                                    URLString:urlStr
                                    parameters:mainparams
                                    constructingBodyWithBlock:nil
                                    error:nil];
    
    YYFTAFHTTPSessionManager *sessionManager = [YYFTAFHTTPSessionManager manager];
    sessionManager.responseSerializer = [YYFTAFHTTPResponseSerializer serializer];
    [[sessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSDictionary *resultDict = [NSDictionary new];
        if (!error && responseObject) {
            NSError *pError = nil;
            NSData *decodeData = [PywCommonDataDealUtils decode:responseObject];
            if (decodeData) {
                // 解析数据
                resultDict = [NSJSONSerialization JSONObjectWithData:decodeData
                                                             options:NSJSONReadingMutableContainers error:&pError];
                if (pError) {
                    COMLog(@"\n----------%@ Error Des =%@----------",requestMethod,pError.description);
                    COMLog(@"\n----------responseDes = %@----------", response.description);
                    return;
                }
            }else{
                NSString *errorMsg = @"A PHP Error Was Encountered, Undefined Configuration Parameters !";
                COMLog(@"\n---------- %@ ----------",errorMsg);
                [PywCommonMBProgressHUD showError:errorMsg];
            }
            // 回调数据
            complete(resultDict);
        }else{
            COMLog(@"网络请求错误提示：\n%@",error);
        }
    }] resume];
}

#pragma mark - Private Method
/// 公共参数包装
+(NSDictionary *)unifiedParames:(NSDictionary *)parames
{
    PywCommonMutableDictionary *muParames = [PywCommonMutableDictionary dictionary];
    [muParames setDictionary:parames];
    NSString *os = [PywCommonDeviceInfo sharedCommonDeviceInfo].os;
    NSString *imei = [PywCommonDeviceInfo sharedCommonDeviceInfo].uuid;
    NSString *networktype = [PywCommonDeviceInfo sharedCommonDeviceInfo].networktype;
    NSString *model = [PywCommonDeviceInfo sharedCommonDeviceInfo].model;
    NSString *sysVer = [PywCommonDeviceInfo sharedCommonDeviceInfo].sysVersion;
    NSString *sdkVer = [PywCommonPlatformInfo sharedCommonPlatformInfo].ver;
    
    NSString *sdkType = [PywCommonPlatformInfo sharedCommonPlatformInfo].sdk_type;
    NSString *gameVersionCode = [PywCommonPlatformInfo sharedCommonPlatformInfo].gameVersionCode;
    NSString *gameVersionName = [PywCommonPlatformInfo sharedCommonPlatformInfo].gameVersionName;
    NSString *promo_channel = [PywCommonPlatformInfo sharedCommonPlatformInfo].promoChannel;
    NSString *promo_code = [PywCommonPlatformInfo sharedCommonPlatformInfo].promoCode;
    NSString *channel_code = [PywCommonPlatformInfo sharedCommonPlatformInfo].channel_code;
    
    [muParames setObject:sdkVer forKey:COMMONSDK_Ver];                      // SDK版本
    [muParames setObject:networktype forKey:COMMONSDK_NetworkType];         // 网络类型
    [muParames setObject:imei forKey:COMMONSDK_Imei];                       // 手机imei
    [muParames setObject:os forKey:COMMONSDK_OS];                           // 运行设备
    [muParames setObject:model forKey:COMMONSDK_Model];                     // 手机型号
    [muParames setObject:sysVer forKey:COMMONSDK_IOSVER];                   // 系统版本号
    
    [muParames setObject:sdkType forKey:COMMONSDK_SdkType];                 // SDK端
    [muParames setObject:gameVersionCode forKey:COMMONSDK_GameVerCode];     // 游戏版本号
    [muParames setObject:gameVersionName forKey:COMMONSDK_GameVerName];     // 游戏版本名
    [muParames setObject:promo_code forKey:COMMONSDK_PromoCode];            // 推广渠道号
    [muParames setObject:promo_channel forKey:COMMONSDK_PromoChannel];      // 推广渠道名
    [muParames setObject:channel_code forKey:COMMONSDK_Channel_Code];       // 联运包ID
    COMLog(@"**** 公共参数 ****\n%@",muParames.description);
    return [muParames copy];
}

@end
